package com.huixin.powermonitor.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huixin.powermonitor.common.CodeUtils;
import com.huixin.powermonitor.common.QueryPageParam;
import com.huixin.powermonitor.common.Result;
import com.huixin.powermonitor.entity.Bike;
import com.huixin.powermonitor.entity.Order;
import com.huixin.powermonitor.service.BikeService;
import com.huixin.powermonitor.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huixin
 * @since 2025-02-21
 */
@RestController
@RequestMapping("/order")
@Api(tags = "订单管理接口")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private BikeService bikeService;

    @GetMapping("/list")
    @ApiOperation("获取所有订单列表")
    public List<Order> list(){
        return orderService.list();
    }

    @PostMapping("/save")
    @ApiOperation("创建新订单")
    public Result save(@RequestBody Order order){
        List<Order> list = orderService.lambdaQuery().eq(Order::getUser, order.getUser()).eq(Order::getBike,order.getBike())
                .ne(Order::getStatus, 2).list();
        if(list.size() > 0){
            return Result.fail("您存在未完成的订单，无法再次下单！");
        }

        order.setCreateTime(LocalDateTime.now());
        order.setOrderCode(CodeUtils.orderCode());
        return orderService.save(order) ? Result.suc("新增成功") : Result.fail("新增失败");

    }

    @GetMapping("/ensure/{id}")
    @ApiOperation("订单结算（确认使用结束）")
    public Result ensure(@PathVariable Integer id){
        Order order = orderService.getById(id);
        order.setFinishTime(LocalDateTime.now());
        Bike bike = bikeService.getById(order.getBike());
        order.setUseTime(CodeUtils.calculateAndSetUserTime(order.getFinishTime(), order.getCreateTime()));
        order.setMoney(CodeUtils.calacMoney(order.getUseTime(), bike));
        order.setStatus(1);
        return orderService.updateById(order) ? Result.suc("结单成功") : Result.fail("结单失败");
    }

    @Transactional
    @GetMapping("/pay/{id}")
    @ApiOperation("订单支付")
    public Result pay(@PathVariable Integer id){
        Order order = orderService.getById(id);
        order.setPayTime(LocalDateTime.now());
        order.setStatus(2);
        return orderService.updateById(order) ? Result.suc("支付成功") : Result.fail("支付失败");
    }

    @GetMapping("/info/{id}")
    @ApiOperation("获取订单详情")
    public Result info(@PathVariable("id") Long id) {
        Order chargeorder = orderService.getById(id);
        return Result.suc(chargeorder);
    }

    @Transactional
    @PostMapping("/deleteBatch")
    @ApiOperation("批量删除订单")
    public Result deleteBatch(@RequestBody Long[] ids) {
        orderService.removeByIds(Arrays.asList(ids));
        return Result.suc("删除成功");
    }

    @PostMapping("/listPage")
    @ApiOperation("分页查询订单")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String user = String.valueOf(param.get("user"));
        String bike = String.valueOf(param.get("bike"));
        String status = String.valueOf(param.get("status"));
        Page<Order> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        /*模糊查询*/
        if (StringUtils.isNotBlank(bike) && !"null".equals(bike)) {
            wrapper.like(Order::getBike, bike);
        }
        if (StringUtils.isNotBlank(user) && !"null".equals(user)) {
            wrapper.eq(Order::getUser, user);
        }
        if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
            wrapper.eq(Order::getStatus, status);
        }
        //返回结果封装
        IPage result = orderService.PageList(page, wrapper);

        return Result.suc(result.getTotal(), result.getRecords());
    }
}